package com.bjtang.upload.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bjtang.upload.dto.DataDto;

@Validated
@RestController
@RequestMapping(value = "/")
public class UploadController {
	@GetMapping("text")
	public String cx() throws IOException {
		// Linux
		// String classpath = ResourceUtils.getURL("classpath:").getPath();
		// classpath = classpath+"../../../ROOT/json/name.txt";
		// windows
		// String classpath = ResourceUtils.getURL("classpath:").getPath();
		byte[] bytes = Files.readAllBytes(Paths.get("..\\..\\..\\ROOT\\json\\name.txt"));
		String content = new String(bytes, StandardCharsets.UTF_8);
		return content;
	}

	@GetMapping("text2")
	public String cx2() throws IOException, URISyntaxException {
		// String property = System.getProperty("user.dir");
		String classpath = ResourceUtils.getURL("classpath:").toURI().toString();
		// URL url = ResourceUtils.getURL("classpath:");
		// URI uri = url.toURI();
		// uri.getPath();

		System.err.println(classpath);
		classpath = classpath.replace("upload/WEB-INF/classes/", "");
		classpath = classpath + "json-data/";

		String fileName = "1.txt";
		classpath = classpath + fileName;
		URI uri = new URL(classpath).toURI();
		System.err.println(uri.getPath());
		Path path = Paths.get(uri);

		if (Files.isReadable(path)) {
			byte[] bytes = Files.readAllBytes(Paths.get(uri));
			return new String(bytes, StandardCharsets.UTF_8);
		} else {
			return "404";
		}
	}

	@PostMapping("/")
	public String Add(@RequestBody DataDto dataDto) throws IOException, URISyntaxException {
		String fileName = dataDto.getDataName() + ".json";
		// String filePath = "/home/bjtang/桌面/zq-gis/项目/测试文件/json/";
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/";
		filePath = filePath + fileName;
		URI uri = new URL(filePath).toURI();
		File file = new File(uri);

		// 2020/5/11 由于windows默认编码为gbk,所以废弃
		// try (FileOutputStream fileOutputStream = new FileOutputStream(file))
		// {
		// fileOutputStream.write(dataDto.getData().getBytes());
		// fileOutputStream.close();
		// }
		OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
		BufferedWriter bdw = new BufferedWriter(os);
		bdw.write(dataDto.getData());
		bdw.close();
		os.close();

		System.err.println(dataDto.getData());
		return filePath + fileName;
	}

	@PutMapping("/")
	public String Put(@RequestBody DataDto dataDto) throws IOException, URISyntaxException {
		String fileName = dataDto.getDataName() + ".json";
		String fileNewName = dataDto.getDataNewName() + ".json";
		// String filePath = "/home/bjtang/桌面/zq-gis/项目/测试文件/json/";
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/";
		URI uri = new URL(filePath + fileNewName).toURI();
		File file = new File(uri);
		// 复制原有文件至bank文件夹
		bank(2, fileName);

		// 删除原有文件
		URI uri2 = new URL(filePath + fileName).toURI();
		File file2 = new File(uri2);
		if (file2.exists() && file2.isFile()) {
			file2.delete();
		}

		// try (FileOutputStream fileOutputStream = new FileOutputStream(file))
		// {
		// fileOutputStream.write(dataDto.getData().getBytes());
		// fileOutputStream.close();
		// }
		OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
		BufferedWriter bdw = new BufferedWriter(os);
		bdw.write(dataDto.getData());
		bdw.close();
		os.close();
		// System.err.println(dataDto.getData());
		return filePath + fileName;
	}

	@DeleteMapping("/")
	public String Del(@RequestBody DataDto dataDto) throws IOException, URISyntaxException {
		String fileName = dataDto.getDataName() + ".json";
		// String filePath = "/home/bjtang/桌面/zq-gis/项目/测试文件/json/";
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/";
		filePath = filePath + fileName;
		URI uri = new URL(filePath).toURI();
		File file = new File(uri);
		bank(1, fileName);
		if (file.exists() && file.isFile()) {
			file.delete();
			return filePath + fileName;
		} else {
			return "404";
		}
	}

	@GetMapping("/{name}")
	public String Get(@PathVariable String name) throws IOException, URISyntaxException {
		String fileName = name + ".json";
		// String filePath = "/home/bjtang/桌面/zq-gis/项目/测试文件/json/";
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/";
		filePath = filePath + fileName;
		URI uri = new URL(filePath).toURI();

		Path path = Paths.get(uri);
		if (Files.isReadable(path)) {
			byte[] bytes = Files.readAllBytes(Paths.get(uri));
			return new String(bytes, StandardCharsets.UTF_8);
		} else {
			return "404";
		}

	}

	@GetMapping("/name")
	public String Get() throws IOException, URISyntaxException {
		String fileName = "name.txt";
		// String filePath = "/home/bjtang/桌面/zq-gis/项目/测试文件/json/name/";
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/name/";
		filePath = filePath + fileName;
		URI uri = new URL(filePath).toURI();
		Path path = Paths.get(uri);
		if (Files.isReadable(path)) {
			byte[] bytes = Files.readAllBytes(Paths.get(uri));
			return new String(bytes, StandardCharsets.UTF_8);
		} else {
			return "404";
		}

	}

	@GetMapping("/list")
	public String GetList() throws IOException, URISyntaxException {
		List<String> list = new ArrayList<String>();
		// String filePath = "/home/bjtang/桌面/zq-gis/项目/测试文件/json/";
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/";
		URI uri = new URL(filePath).toURI();
		File file = new File(uri);
		if (file.isDirectory()) {
			File[] listFiles = file.listFiles();
			for (int i = 0; i < listFiles.length; i++) {
				if (listFiles[i].isFile()) {
					String name = listFiles[i].getName();
					if (name.indexOf(".json") != -1) {
						String substring = name.substring(0, name.indexOf(".json"));
						list.add(substring);
					}
				}
			}
		}
		return String.join(",", list);
	}

	void bank(int tab, String fileName) throws IOException, URISyntaxException {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
		String time = sdf.format(date);
		String suffix = "";
		if (tab == 1) {
			suffix = ".del";
		} else if (tab == 2) {
			suffix = ".update";
		}
		String filePath = ResourceUtils.getURL("classpath:").toURI().toString();
		filePath = filePath.replace("upload/WEB-INF/classes/", "");
		filePath = filePath + "json-data/";
		filePath = filePath + fileName;
		URI uri = new URL(filePath).toURI();
		Path path = Paths.get(uri);
		if (Files.isReadable(path)) {
			byte[] bytes = Files.readAllBytes(Paths.get(uri));

			String filePath2 = ResourceUtils.getURL("classpath:").toURI().toString();
			filePath2 = filePath2.replace("upload/WEB-INF/classes/", "");
			filePath2 = filePath2 + "json-data/bank/";
			filePath2 = filePath2 + time + fileName + suffix;
			URI uri2 = new URL(filePath2).toURI();
			File file2 = new File(uri2);
//			try (FileOutputStream fileOutputStream = new FileOutputStream(file2)) {
//				fileOutputStream.write(bytes);
//				fileOutputStream.close();
//			}
			OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file2), "utf-8");
			BufferedWriter bdw = new BufferedWriter(os);
			bdw.write(new String(bytes, StandardCharsets.UTF_8));
			bdw.close();
			os.close();
		}
	}
}
